package tech.hdis.framework.response;


import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 基础返回值
 *
 * @author 黄志文
 */
@Getter
@Setter
@ToString
public class RestfulResponse {

    /**
     * 初始化RestfulResponse
     *
     * @return RestfulResponse
     */
    public static RestfulResponse getInstance() {
        return new RestfulResponse();
    }

    /**
     * 返回码-成功
     *
     * @return RestfulResponse
     */
    public RestfulResponse success() {
        this.code = SuccessProperties.SUCCESS_KEY;
        this.message = SuccessProperties.SUCCESS_VALUE;
        return this;
    }

    /**
     * 返回码组装
     *
     * @param code 返回码
     * @return RestfulResponse
     */
    public RestfulResponse code(@NonNull String code) {
        this.code = code;
        this.message = RestfulResponseDic.get(code);
        return this;
    }

    /**
     * 非结构化数据组装
     *
     * @param value 非结构化数据
     * @return RestfulResponse
     */
    public RestfulResponse result(@NonNull Object value) {
        if (StringUtils.isEmpty(this.code) || StringUtils.isEmpty(this.message)) {
            throw new NullPointerException("RestfulResponse's code and message can't be null!");
        }
        if (value == null) {
            throw new NullPointerException("RestfulResponse's method single's param value can't be null!");
        }
        if (data == null) {
            data = new HashMap<>(16);
        }
        this.data.put("result", value);
        return this;
    }

    /**
     * 多个非结构化数据组装
     *
     * @param value 非结构化数据key
     * @param value 非结构化数据value
     * @return RestfulResponse
     */
    public RestfulResponse result(@NonNull String key, @NonNull Object value) {
        if (StringUtils.isEmpty(this.code) || StringUtils.isEmpty(this.message)) {
            throw new NullPointerException("RestfulResponse's code and message can't be null!");
        }
        if (StringUtils.isEmpty(key) || value == null) {
            throw new NullPointerException("RestfulResponse's method multiple's param key and value can't be null!");
        }
        if (this.data == null) {
            this.data = new HashMap<>(16);
        }
        this.data.put(key, value);
        return this;
    }

    /**
     * 返回码
     */
    private String code;
    /**
     * 附带消息
     */
    private String message;
    /**
     * 非结构化数据
     */
    private Map<String, Object> data;
}
